package org.elsfs.cloud.common.mybatis.ext.sql.support.select;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.util.lang.NamingCase;
import org.elsfs.cloud.common.util.lang.StringUtils;

import java.util.regex.Pattern;

/**
 * 标准选择项实现
 *

 */
@Getter
@RequiredArgsConstructor
public class StandardSelectItem implements SelectItem {

    /**
     * 字段别名分割正则模式
     */
    private static final Pattern FIELD_ALIAS_SPLITTING_PATTERN = Pattern.compile("( +as +(?=\\w+$))|( +(?=\\w+$))", Pattern.CASE_INSENSITIVE);

    /**
     * 字段所属表别名
     */
    private final String tableAlias;

    /**
     * 字段名称
     */
    private final String field;

    /**
     * 字段名别
     */
    private final String fieldAlias;

    public StandardSelectItem(String field) {
        if (StringUtils.isBlank(field)) {
            throw new MybatisPlusException( "选择字段不能为空");
        }

        String alias = null;
        if (field.contains(".")) {
            final String[] parts = field.split("\\.");

            if (parts.length == 2) {
                alias = parts[0];
                field = parts[1];
            }
        }

        String[] tokens = FIELD_ALIAS_SPLITTING_PATTERN.split(field);
        if (tokens.length == 0) {
            throw new MybatisPlusException( "选择字段不能为空");
        }

        if (tokens.length == 1) {
            this.tableAlias = alias;
            this.field = tokens[0];
            this.fieldAlias = null;
            return;
        }

        this.tableAlias = alias;
        this.field = tokens[0];
        this.fieldAlias = tokens[1];
    }

    /**
     * 构建SQL片段
     *
     * @return SQL片段
     */
    @Override
    public String buildSqlFragment() {
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotBlank(this.tableAlias)) {
            stringBuilder.append(this.tableAlias)
                .append(".");
        }
        if (StringUtils.isBlank(this.fieldAlias)) {
            stringBuilder.append(NamingCase.toUnderlineCase(this.field));
        } else {
            stringBuilder.append(NamingCase.toUnderlineCase(this.field))
                .append(" AS ")
                .append(NamingCase.toUnderlineCase(this.fieldAlias));
        }

        return stringBuilder.toString();
    }
}
